import JSZip from 'jszip'
import {downFile} from '@/util/common'
import { Dictionary } from '@/api/config'
export interface GenerateZip{
  type:'base64'|'arrayBuffer'|'blob'
  name:string,
  data:string|ArrayBuffer|Blob
}

//生成zip文件
const generateZip = (zip:JSZip, configs:Array<GenerateZip>) => {
  //防止重名
  const nameHash:Dictionary<number> = {}
  configs.forEach((config) => {
    const {name} = config
    if (nameHash[name] === undefined) nameHash[name] = 0
    else nameHash[name] += 1
    const duplicateNum = nameHash[name]
    zip.file(duplicateNum ? name + '(' + duplicateNum + ')' : name, config.data, {base64:config.type === 'base64'})
  })
  return zip.generateAsync({type:'arraybuffer'})
}

//防止重名
export const preventDuplicate = (configs:Array<GenerateZip>, suffix:string) => {
  const nameHash:Dictionary<number> = {}
  configs.forEach((config) => {
    const {name} = config
    if (nameHash[name] === undefined) nameHash[name] = 0
    else nameHash[name] += 1
    const duplicateNum = nameHash[name]
    const useName = duplicateNum ? name + '(' + duplicateNum + ')' : name
    config.name = useName + suffix
  })
}

//下载zip文件
export const downZip = (fileName:string, configs:Array<GenerateZip>) => {
  return new Promise<null>((resolve, reject) => {
    const zip = new JSZip()
    generateZip(zip, configs).then((buffer) => {
      downFile(fileName, buffer)
      resolve(null)
    }).catch((error) => {
      reject(error)
    })
  })
}